import React, { Component } from 'react';

class CommentItem extends Component{
  constructor(){
    super()
    this.state = {
      timeString: ''
    }
  }

  

  componentWillMount(){
    this.toStringTime()
    this.timer= setInterval(() => {
      this.toStringTime()
    }, 5000)
  }

  componentWillUnmount(){
    clearInterval(this.timer)
  }
  
  render(){
    return (
      <div className="comment">
         <div className='comment-user'>
          <span>{this.props.comment.name} </span>：
        </div>
        <p>{this.props.comment.content}</p>
        <span className='comment-createdtime'>
          {this.state.timeString}
        </span>
        <span className='comment-delete' onClick={this.handleDeleteComment.bind(this)}>
          删除
        </span>
      </div>
    )
  }

  toStringTime(){
    const comment = this.props.comment;
    const duration = Math.round(new Date().getTime()/1000 - comment.createdTime)
    this.setState({
      timeString: duration>60?`${Math.round(duration/60)}分钟前`: `${Math.max(duration, 1)}秒前`
    })
  }

  handleDeleteComment(){
    if(this.props.onDelete){
      this.props.onDelete({index: this.props.index})
    }
  }
}

export default CommentItem